//
// Created by jmdvirus on 2020/3/27 下午5:18.
// Copyright (c) 2020 benewtech All rights reserved.
//
//     ******          *             *--*
//       ||            *             |
//       ||  *--*--*---*  * *-********--*
//   *  //   *  *  *   *\ / ||  |  |    |
//    **    *  *  *---* *  *   *--* *--*
//

#include "CMMediaOperationRaw.h"
#include "cm_logprint.h"

CMMediaOperationRaw::CMMediaOperationRaw()
{
    memset(&m_camera, 0, sizeof(camera_handle));
}

CMMediaOperationRaw::~CMMediaOperationRaw()
{
    cm_camera_deinit(&m_camera);
}

int CMMediaOperationRaw::open(int index)
{
    int ret = cm_camera_init(&m_camera, index, m_width, m_height);
    if (ret < 0)
    {
        return -10 + ret;
    }
    ret = cm_camera_open(&m_camera);
    if (ret < 0)
    {
        cmerror("open failed [%d]\n", ret);
        return -20 + ret;
    }
    ret = cm_camera_start(&m_camera);
    if (ret < 0)
    {
        cmerror("camera start error [%d]\n", ret);
        return -30 + ret;
    }
    return 0;
}

int CMMediaOperationRaw::close()
{
    cm_camera_stop(&m_camera);
    cm_camera_close(&m_camera);
    cminfo("camera close done\n");
    return 0;
}

int CMMediaOperationRaw::readYUV(unsigned char **data)
{
    int ret = cm_camera_stream_get(&m_camera, m_buf, m_bufSize);
    int c = 0;
    while (ret == EAGAIN && c++ < 10)
    {
        ret = cm_camera_stream_get(&m_camera, m_buf, m_bufSize);
    }
    if (ret < 0)
    {
        return -10 + ret;
    }
    if (data)
        *data = m_buf;
    return m_bufSize;
}

bool CMMediaOperationRaw::isOpened()
{
    return m_camera.videofd > 0;
}
int CMMediaOperationRaw::readYUV(unsigned char **data, size_t *len)
{
    int ret = cm_camera_stream_get2(&m_camera, data, len);
    return ret;
}
void CMMediaOperationRaw::readClear()
{
    cm_camera_stream_qbuf(&m_camera);
}
